<template>
  <EmapForm
    ref="emapFormRef"
    :options='formOptions'
    :datas="datas"
    :models="models"
    :outline="false"
    :formUrl="formUrl"
    @change="formChange"
    @global-event="onGlobalEvent"
  >
  </EmapForm>
</template>

<script>
import { EmapForm } from 'bh-vue'

export default {
  name: 'sub-form',
  props: {
    item: Object,
    models: Object,
    datas: Object,
    options: Object,
    appName: Object,
    formUrl: String
  },
  data() {
    return {
      fileData: {},
      oneFileData: {},
    }
  },
  created () {
    this.cachedMap = {}
  },
  computed: {
    renderList() {
      const { item, models } = this
      const cachedKey = this.cacheKey(item, models)

      if (this.cachedMap && this.cachedMap[cachedKey]) {
        return this.cachedMap[cachedKey]
      }

      if (!models || !item) {
        // eslint-disable-next-line vue/no-side-effects-in-computed-properties
        this.cachedMap[cachedKey] = []
        return []
      }

      const modelsMeta = models.meta = (models.meta || []).map(element => {
        const newItem = { ...element }
        if(!newItem.caption){
          newItem.caption = newItem.name
        }

        if (newItem.url) {
          const dicId = newItem.url ? newItem.url.match(/\/dic\/(\S*).do/)[1] : ''
          const thirdParams = newItem.url ? "sign=" + models.supportSigns[dicId] + "&time=" + models.time : ''
          if (thirdParams && newItem.url.indexOf(thirdParams) === -1) {
            newItem.url = newItem.url + "?" + thirdParams
          }
        }

        return newItem
      })

      let newArray = []
      const modelsArr = item.options.models
      modelsArr.forEach((element, index) => {
          newArray[index] = modelsMeta.filter((item) => {
              return item.name === element
          })[0]
      })
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties
      this.cachedMap[cachedKey] = newArray
      return newArray
    },
    formOptions() {
      const { options } = this
      const { key } = this.datas || {}
      const _this = this
      // window['tg-turing'].utils.getContextPath() + window.contextPath
      let getFileUrl = window.contextPath + _this.formUrl.replace('showForm', 'getFile')
      let getPreviewFile = window.contextPath + _this.formUrl.replace('showForm', 'previewFile')
      if(window.formOnly){
        getFileUrl = "getFile.do"
        getPreviewFile = "previewFile.do"
      }

      return {
        pagePath: _this.renderList,
        modelName: 'FORM_GROUP',
        validate: true,//是否开启校验
        // renderByGroup: true, // 按照分组渲染表单
        autoColumn: true, //只读表单列宽自动补齐
        readonly: options && options.readonly,
        inputWidth: 12,
        mode: 't',
        cols: 12,
        defaultOptions: {
          uploadfile: {
            uploadUrl: window.contextPath + '/sys/' + _this.appName.name + '/upload.do',
            fileSrc: getFileUrl,
            previewSrc: getPreviewFile,
            fileParams: {
              key: JSON.stringify(key),
              itemName: "",
              fileName: "",
            },
            add: (e, data) => {
              data.paramName = 'fdata'
            },
            onSuccess: (data)=> {
              const uploadDatas = []
              let returnData = {}

              if(data && data.result && data.result.datas){
                if(JSON.stringify(data.result.datas).indexOf(JSON.stringify(uploadDatas)) === -1){
                  uploadDatas.push(data.result.datas)
                }
                const result = data.result

                returnData ={
                  ...data,
                  result:{
                    ...data.result,
                    success: result.code ==='0',
                    name: result.datas.name,
                  },
                }
              }else{
                returnData = {
                  ...data,
                  ...returnData,
                  success: false,
                  result: {
                    error: data && data.result && data.result.msg
                  }
                }
              }
              
              return returnData
            },
            //下载附件
            getDownloadUrl: (file) => {
              const getFileURL = "getFile.do"  //需要拼接  showForm.do后面
              const idKey = JSON.stringify(key)
              let taskId = ""  //taskId可以先不要    showForm里面的data获取taskId    如果没有字段不传
              const WID = JSON.stringify(idKey)  //取对应bizkey
              //获取模型的时间
              const lastTime = file.lastModified
              const fileName = file.name //当前附件名字
              let itemName = "附件" //模型字段名称
              return getFileURL + "?taskId=" + taskId + "&key="+ key +"&WID=" + WID + "&time=" + lastTime + "&fileName=" + fileName + "&itemName=" + itemName
            },
            done: (e, data, uploadFiles) => {
              //上传成功进行保存相关数据
              const result = data.result
              if(result.code === "0"){
                //处理附件上传数据在获取表单数据时进行追加
                const datas = result.datas
                let oneData = {}
                oneData[datas.name] = {
                  ...datas
                }
                let uploadEdData = {}
                if(uploadFiles){
                  for(var key in uploadFiles){
                    uploadEdData[key] = uploadFiles[key]
                  }
                }
                Object.assign(_this.oneFileData, oneData, uploadEdData)
                let fileName = $(e.target).closest('div[xtype="uploadfile"]').data("name")
                _this.fileData[fileName] = _this.oneFileData
              }
            },
            onDelete: (item)=> {
              
              const fileName = $(item).parents('div[data-type="Clob"]').data("name")
              const title = $(item).find(".bh-file-upload-filename").attr("title")
              for(var key in _this.fileData){
                if(key === fileName){
                  for(var childKey in _this.fileData[key]){
                    if(childKey === title){
                      delete _this.fileData[key][childKey]
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  components: {
    EmapForm
  },
  methods: {
    onGlobalEvent(...args) {
      this.$emit('global-event', ...args)
    },
    cacheKey (item, models) {
      const itemKey = item && item.options && item.options.models && item.options.models.join('_') || ''
      const modelsKey = models && models.meta && models.meta.map(item => item.name) || ''
      return `cached_${itemKey}_${modelsKey}`
    },
    formChange(e, value) {
      if(e){
        this.$emit('form-change', e)
        Vue.nextTick(() => {
          this.$emit('change', this.getValue())
        })
      }else{
        this.$emit('change', null, value)
      }
    },
    getValue () {
      let data = this.$refs.emapFormRef.getValue()
      if(JSON.stringify(this.fileData) !== "{}"){
        for(let key in this.fileData){
          data[key] = this.fileData[key]
        }
      }
      return data
    },
    setValue (val) {
      return this.$refs.emapFormRef.setValue(val)
    },
    validate () {
      return this.$refs.emapFormRef.validate()
    }
  },
}
</script>
